<script setup>
import { ref, onMounted, computed } from "vue";
import { userStore } from "@/stores/userStore";
import { interceptor } from "@/utils/interceptor";
import { ElMessage } from "element-plus";
const userUserStore = userStore();

// 过滤条件
const filterType = ref("1");
const filterName = ref("");

// 题目分类
const singleQuestions = ref([]); // 单选题
const multiQuestions = ref([]); // 多选题
const judgmentQuestions = ref([]); // 判断题
const subjectiveQuestions = ref([]); // 主观题

// 用户作答状态
const selectedSingleAnswers = ref({}); // 单选题选中答案
const selectedMultiAnswers = ref({}); // 多选题选中答案
const selectedJudgmentAnswers = ref({}); // 判断题选中答案
const subjectiveAnswers = ref({}); // 主观题文本框答案

// 页面挂载时添加滚动监听和加载数据
onMounted(() => {
  const httpInstance = interceptor();
  httpInstance
    .post(`/student/mistakeCollection/page`, {
      id: userUserStore.id,
    })
    .then((res) => {
      console.log("API 返回的数据:", res.data.data);

      if (!res.data.data) {
        console.error("数据格式错误: questions 不存在或不是数组");
        return;
      }

      // 分类题目
      res.data.data.forEach((question) => {
        switch (question.type) {
          case 1: // 单选题
            singleQuestions.value.push({
              userId: userStore.id,
              id: question.id,
              question: question.questionId,
              title: question.topic,
              options: [
                question.optionA,
                question.optionB,
                question.optionC,
                question.optionD,
              ].filter(Boolean), // 过滤掉空值
              answer: question.answer, // 正确答案
            });
            break;
          case 2: // 多选题
            multiQuestions.value.push({
              id: question.id,
              question: question.questionId,
              title: question.topic,
              options: [
                question.optionA,
                question.optionB,
                question.optionC,
                question.optionD,
              ].filter(Boolean), // 过滤掉空值
              answer: question.answer.split(""), // 正确答案（多选题可能有多个答案）
            });
            break;
          case 3: // 判断题
            judgmentQuestions.value.push({
              id: question.id,
              question: question.questionId,
              title: question.topic,
              options: ["对", "错"],
              answer: question.answer, // 正确答案
            });
            break;
          case 4: // 主观题
            subjectiveQuestions.value.push({
              id: question.id,

              question: question.questionId,
              title: question.topic,
              answer: question.answer, // 正确答案
            });
            break;
          default:
            console.warn(`未知题目类型: ${question.type}`);
            break;
        }
      });

      // 填充用户已选答案
      res.data.data.forEach((selectedQuestion) => {
        const questionId = selectedQuestion.questionId;
        const selectedAnswer = selectedQuestion.selectQuestion;

        if (singleQuestions.value.some((q) => q.question === questionId)) {
          selectedSingleAnswers.value[questionId] = selectedAnswer;
        } else if (multiQuestions.value.some((q) => q.question === questionId)) {
          selectedMultiAnswers.value[questionId] = selectedAnswer.split("");
        } else if (judgmentQuestions.value.some((q) => q.question === questionId)) {
          selectedJudgmentAnswers.value[questionId] = selectedAnswer;
        } else if (subjectiveQuestions.value.some((q) => q.question === questionId)) {
          subjectiveAnswers.value[questionId] = selectedAnswer;
        } else {
          console.warn(`无法匹配的题目 ID: ${questionId}`);
        }
      });
    });
});

// 过滤属性
const filteredQuestions = computed(() => {
  let result = [];
  // 根据题目类型过滤
  if (filterType.value === "1") {
    result = singleQuestions.value;
  } else if (filterType.value === "2") {
    result = multiQuestions.value;
  } else if (filterType.value === "3") {
    result = judgmentQuestions.value;
  } else if (filterType.value === "4") {
    result = subjectiveQuestions.value;
  } else {
    // 如果未选择类型，则显示所有题目
    result = [
      ...singleQuestions.value,
      ...multiQuestions.value,
      ...judgmentQuestions.value,
      ...subjectiveQuestions.value,
    ];
  }
  // 根据题目名称模糊匹配
  if (filterName.value.trim()) {
    const keyword = filterName.value.trim().toLowerCase();
    result = result.filter((question) => question.title.toLowerCase().includes(keyword));
  }

  return result;
});

// 删除错题
const deleMistake = (question) => {
  if (confirm("确认要删除吗？")) {
    const httpInstance = interceptor();
    httpInstance
      .delete(`student/mistakeCollection/${question.id}`)
      .then((res) => {
        console.log(res);
        alert("删除成功！");
        // 根据题目类型从对应的数组中移除
        if (singleQuestions.value.some((q) => q.question === question.question)) {
          singleQuestions.value = singleQuestions.value.filter(
            (q) => q.question !== question.question
          );
        } else if (multiQuestions.value.some((q) => q.question === question.question)) {
          multiQuestions.value = multiQuestions.value.filter(
            (q) => q.question !== question.question
          );
        } else if (judgmentQuestions.value.some((q) => q.question === question.question)) {
          judgmentQuestions.value = judgmentQuestions.value.filter(
            (q) => q.question !== question.question
          );
        } else if (subjectiveQuestions.value.some((q) => q.question === question.question)) {
          subjectiveQuestions.value = subjectiveQuestions.value.filter(
            (q) => q.question !== question.question
          );
        }
      })
      .catch((err) => {
        console.log("删除失败", err);
        ElMessage.error("删除失败，清稍后重试");
      });
  }
};
</script>

<template>
  <div class="input">
    <span class="title">题目名称</span>
    <input type="content" placeholder="请输入" v-model="filterName" />

    <span class="title">题目类型</span>
    <select v-model="filterType">
      <option value="1">单选题</option>
      <option value="2">多选题</option>
      <option value="3">判断题</option>
      <option value="4">主观题</option>
    </select>
  </div>

  <!-- 单选题 -->
  <div class="select" v-if="filterType === '1'">
    <span class="word">单选题</span>
    <div v-if="filteredQuestions && filteredQuestions.length > 0">
      <div v-for="question in filteredQuestions" :key="question.question" class="question">
            <span class="title">{{ question.title }}</span>
            <div class="options">
              <div v-for="(option, optionIndex) in question.options" :key="optionIndex" class="option">
                <div class="button-container">
                  <button
                    class="circle-button"
                    :class="{
                      selected:
                        selectedSingleAnswers[question.question] ===
                        String.fromCharCode(65 + optionIndex),
                    }"
                  >
                    {{ String.fromCharCode(65 + optionIndex) }}
                  </button>
                </div>
                <span class="description">{{ option }}</span>
              </div>
              <div class="correct-answer">正确答案：{{ question.answer }}</div>
              <div>
                <el-button type="primary" style="margin-top: 0.5%" @click="deleMistake(question)"
                  >删除错题</el-button
                >
              </div>
            </div>
        </div>
    </div>
    <div v-else class="noData">
      <img src="@/assets/img/noDataView.png" alt="No Data Found"/>
    </div>
  </div>

  <!-- 多选题 -->
   
    <div class="select" v-if="filterType === '2'">
      <span class="word">多选题</span>
      <div v-if="filteredQuestions && filteredQuestions.length>0">
        <div v-for="question in filteredQuestions" :key="question.question" class="question">
          <span class="title">{{ question.title }}</span>
          <div class="options">
            <div v-for="(option, optionIndex) in question.options" :key="optionIndex" class="option">
              <div class="button-container">
                <button
                  class="circle-button"
                  :class="{
                    selected: selectedMultiAnswers[question.question]?.includes(
                      String.fromCharCode(65 + optionIndex)
                    ),
                  }"
                >
                  {{ String.fromCharCode(65 + optionIndex) }}
                </button>
              </div>
              <span class="description">{{ option }}</span>
            </div>
            <div class="correct-answer">正确答案：{{ Array.isArray(question.answer) ? question.answer.join('') : question.answer }}</div>
            <div>
              <el-button type="primary" style="margin-top: 0.5%" @click="deleMistake(question)"
                >删除错题</el-button
              >
            </div>
          </div>
        </div>
      </div>
      <div v-else class="noData">
        <img src="@/assets/img/noDataView.png" alt="No Data Found"/>
      </div>
    </div>
  

  <!-- 判断题 -->
  <div class="select" v-if="filterType === '3'">
    <span class="word">判断题</span>
    <div v-if="filteredQuestions && filteredQuestions.length > 0">
      <div v-for="question in filteredQuestions" :key="question.question" class="question">
      <span class="title">{{ question.title }}</span>
      <div class="options">
        <div v-for="(option, optionIndex) in question.options" :key="optionIndex" class="option">
          <div class="button-container">
            <button
              class="circle-button"
              :class="{
                selected:
                  selectedJudgmentAnswers[question.question] ===
                  String.fromCharCode(65 + optionIndex),
              }"
            >
              {{ String.fromCharCode(65 + optionIndex) }}
            </button>
          </div>
          <span class="description">{{ option }}</span>
        </div>
        <div class="correct-answer">正确答案：{{ question.answer }}</div>
        <div>
          <el-button type="primary" style="margin-top: 0.5%" @click="deleMistake(question)"
            >删除错题</el-button
          >
        </div>
      </div>
    </div>
    </div>
    <div v-else class="noData">
        <img src="@/assets/img/noDataView.png" alt="No Data Found"/>
      </div>
  </div>

  <!-- 主观题 -->
  <div class="select" v-if="filterType === '4'">
    <span class="word">主观题</span>
    <div v-if="filteredQuestions && filteredQuestions.length > 0">
      <div v-for="question in filteredQuestions" :key="question.question" class="question">
      <span class="title">{{ question.title }}</span>
      <div class="text-area">
        <textarea
          v-model="subjectiveAnswers[question.question]"
          placeholder="请输入您的答案..."
          rows="4"
          class="answer-textarea"
          :disabled="true"
        ></textarea>
        <div class="correct-answer">正确答案：{{ question.answer }}</div>
        <div>
          <el-button type="primary" style="margin-top: 0.5%" @click="deleMistake(question)"
            >删除错题</el-button
          >
        </div>
       </div>
    </div>
    </div>
    <div v-else class="noData">
      <img src="@/assets/img/noDataView.png" alt="No Data Found"/>
    </div>
  </div>
</template>

<style scoped lang="scss">
.input {
  display: flex;
  margin-left: 6%;
  margin-top: 4%;
  flex-direction: row;

  .title {
    font-size: 190%;
    margin-right: 2%;
  }
  input {
    font-size: 150%;
    margin-right: 5%;
  }
  select {
    width: 15%;
    margin-right: 2%;
    font-size: 150%;
    color: rgb(145, 145, 145);
    option {
      font-size: 100%;
    }
  }
}

.head {
  width: 100vw;
  height: 12vh;
  display: flex;
  flex-direction: row;
  border-bottom: 1px solid rgb(132, 132, 132);
  transition: all 0.3s ease; // 平滑过渡效果
  background-color: white;
  .stu_info {
    width: 30%;
    height: 100%;
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: flex-start;

    .info-item {
      display: flex;
      flex-direction: column;
      align-items: flex-end;
      justify-content: center;
      width: 20%;
      padding-right: 10px;
      font-size: 120%;
      color: rgb(95, 95, 95);

      span {
        margin: 2px 0;
      }
    }

    .info-item1 {
      display: flex;
      flex-direction: column;
      margin-left: 2%;
      justify-content: center;
      width: 30%;
      padding-right: 10px;
      font-size: 120%;
      color: rgb(95, 95, 95);

      span {
        margin: 2px 0;
      }
    }
  }

  .exam_info {
    width: 60%;
    height: 100%;
    display: flex;
    flex-direction: column;

    .exam_name {
      margin-left: 23%;
      margin-top: 1.5%;
      font-size: 250%;
      font-weight: 600;
    }

    .exam_footer {
      margin-left: 20%;

      span {
        margin-right: 20%;
      }
    }
  }

  .button {
    width: 10%;
    height: 100%;
    padding-top: 2.5%;
    padding-left: 3%;
    .el-button {
      &.disabled {
        background-color: gray; // 禁用时的背景颜色
        color: white; // 禁用时的文字颜色
        cursor: not-allowed; // 鼠标悬停时显示禁止状态
        pointer-events: none; // 禁止点击
      }
    }
  }
}
.fixed-header {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  z-index: 1000;
}
.select {
  margin-top: 2%;
  width: 100vw;

  .word {
    margin-left: 2%;
    font-size: 150%;
    font-weight: 600;
  }

  .question {
    display: flex;
    flex-direction: column;

    .title {
      margin-top: 1%;
      margin-left: 2%;
      font-size: 120%;
    }

    .options {
      display: flex;
      flex-direction: column;
      margin-left: 4%;

      .option {
        display: flex;
        flex-direction: row;
        align-items: center; // 垂直居中对齐
        margin-top: 1%; // 每个选项之间的间距
        cursor: pointer; // 鼠标悬停时显示手型

        .button-container {
          width: 2.5%;
          padding-top: 2.5%;
          position: relative;
          background-color: transparent;

          .circle-button {
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            border-radius: 50%;
            color: rgb(19, 19, 19);
            font-size: 16px;
            font-weight: bold;
            border: 1px solid black;
            cursor: pointer;
            display: flex;
            justify-content: center;
            align-items: center;
            text-transform: uppercase;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            transition: background-color 0.3s ease;

            &.selected {
              background-color: rgb(61, 219, 240); // 选中时变为蓝色
              color: white; // 文字颜色变为白色
            }
          }
        }

        .description {
          margin-left: 1%;
          font-size: 125%;
        }
      }
    }

    .text-area {
      margin-top: 1%;
      margin-left: 4%;

      .answer-textarea {
        width: 90%; // 宽度占父容器的90%
        padding: 10px; // 内边距
        font-size: 16px; // 字体大小
        border: 1px solid #ccc; // 边框颜色
        border-radius: 5px; // 圆角
        resize: none; // 禁止用户手动调整大小
        transition: border-color 0.3s ease; // 边框颜色平滑过渡

        &:focus {
          border-color: #007bff; // 聚焦时边框颜色变为蓝色
          outline: none; // 移除默认聚焦轮廓
        }
        &:disabled {
          background-color: #f5f5f5; // 禁用时背景颜色变灰
          color: #aaa; // 文字颜色变浅
        }
      }
    }
  }
  .correct-answer {
    margin-top: 1%;
    font-size: 14px;
    color: rgb(76, 139, 212);
    font-weight: bold;
  }
}

.noData{
max-width: 100%;
height: auto;
margin-left: 18%;
}
</style>
